package com.wtwd.campus.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author pxin
 * @Date create in 16:44 2021/8/10
 * @Description 微信扫码获取签名等条件信息
 */
public class WxScanCodeUtils {
    private static final Logger logger = LoggerFactory.getLogger(WxScanCodeUtils.class);

    private static String appId = "wxb70939670a55edb7";
    private static String secret = "44865d98a5b43332e26e1ab9a1b56115";
    private static String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
    private static String jsApiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?";

    private static String appIdXmly = "wx4c595df7d3e8f309";
    private static String secretXmly = "0d906056287addbb10229d4e57c31e96";
    private static String accessTokenUrlXmly = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appIdXmly + "&secret=" + secretXmly;


    private static String appIdRy = "wxe127a0c95ac1911a";
    private static String secretRy = "a270e9cf5783c5e9902d61e195996e4a";
    private static String accessTokenUrlRy = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appIdRy + "&secret=" + secretRy;
    //创维
    private static final String WX_APP_ID_CW = "wxb27a83d55006efb3";
    private static final String WX_APP_SECRET_CW = "d3f9479fc8d45800a3b08ef8878f0bd8";
    private static String accessTokenUrl_CW = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WX_APP_ID_CW + "&secret=" + WX_APP_SECRET_CW;

    //小湃
    private static final String WX_APP_ID_XB = "wxe7a4758901947953";
    private static final String WX_APP_SECRET_XB = "f57191a4acbfb8294f864d8e85ba2303";
    private static String accessTokenUrl_XB = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WX_APP_ID_XB + "&secret=" + WX_APP_SECRET_XB;

    /**
     * 获取扫描条件信息（微信扫码）
     *
     * @return
     */
    public static Map<String, Object> getScanCodeCondition(String url) {
        //获取Access-Token
        String accessToken = "";
        Map<String, Object> params = new HashMap<>();
        params.put("corpid", appId);
        params.put("corpsecret", secret);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet get = new HttpGet(accessTokenUrl);
        try {
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String s = EntityUtils.toString(entity, "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                accessToken = (String) map.get("access_token");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取Access_token失败");
        }
        //获取jsapiTicket
        String ticket = "";
        HttpGet get2 = new HttpGet(jsApiTicketUrl.concat("access_token=" + accessToken + "&type=jsapi"));
        try {
            CloseableHttpResponse response = httpclient.execute(get2);
            if (response.getEntity() != null) {
                String s = EntityUtils.toString(response.getEntity(), "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                ticket = (String) map.get("ticket");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取jsApiTicket失败");
        }
        //获取signature
        String signature = "";
        String noncestr = UUID.randomUUID().toString();
        long time = System.currentTimeMillis();
        String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + time + "&url=" + url;
        signature = SHA1(str);
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", time);
        map.put("noncestr", noncestr);
        map.put("appId", appId);
        map.put("signature", signature);
        return map;
    }

    /**
     * 获取微信扫码条件创维
     */
    public static Map<String, Object> getScanCodeConditionCW(String url) {
        //获取Access-Token
        String accessToken = "";
        Map<String, Object> params = new HashMap<>();
        params.put("corpid", WX_APP_ID_CW);
        params.put("corpsecret", WX_APP_SECRET_CW);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet get = new HttpGet(accessTokenUrl_CW);
        try {
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String s = EntityUtils.toString(entity, "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                accessToken = (String) map.get("access_token");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取Access_token失败");
        }
        //获取jsapiTicket
        String ticket = "";
        HttpGet get2 = new HttpGet(jsApiTicketUrl.concat("access_token=" + accessToken + "&type=jsapi"));
        try {
            CloseableHttpResponse response = httpclient.execute(get2);
            if (response.getEntity() != null) {
                String s = EntityUtils.toString(response.getEntity(), "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                ticket = (String) map.get("ticket");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取jsApiTicket失败");
        }
        //获取signature
        String signature = "";
        String noncestr = UUID.randomUUID().toString();
        long time = System.currentTimeMillis();
        String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + time + "&url=" + url;
        signature = SHA1(str);
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", time);
        map.put("noncestr", noncestr);
        map.put("appId", WX_APP_ID_CW);
        map.put("signature", signature);
        return map;
    }

    /**
     * 获取微信扫码条件小湃
     */
    public static Map<String, Object> getScanCodeConditionXB(String url) {
        //获取Access-Token
        String accessToken = "";
        Map<String, Object> params = new HashMap<>();
        params.put("corpid", WX_APP_ID_XB);
        params.put("corpsecret", WX_APP_SECRET_XB);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet get = new HttpGet(accessTokenUrl_XB);
        try {
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String s = EntityUtils.toString(entity, "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                accessToken = (String) map.get("access_token");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取Access_token失败");
        }
        //获取jsapiTicket
        String ticket = "";
        HttpGet get2 = new HttpGet(jsApiTicketUrl.concat("access_token=" + accessToken + "&type=jsapi"));
        try {
            CloseableHttpResponse response = httpclient.execute(get2);
            if (response.getEntity() != null) {
                String s = EntityUtils.toString(response.getEntity(), "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                ticket = (String) map.get("ticket");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取jsApiTicket失败");
        }
        //获取signature
        String signature = "";
        String noncestr = UUID.randomUUID().toString();
        long time = System.currentTimeMillis();
        String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + time + "&url=" + url;
        signature = SHA1(str);
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", time);
        map.put("noncestr", noncestr);
        map.put("appId", WX_APP_ID_XB);
        map.put("signature", signature);
        return map;
    }

    /**
     * 获取扫描条件信息（微信扫码）喜马拉雅
     *
     * @return
     */
    public static Map<String, Object> getScanCodeConditionXmly(String url) {
        //获取Access-Token
        String accessToken = "";
        Map<String, Object> params = new HashMap<>();
        params.put("corpid", appIdXmly);
        params.put("corpsecret", secretXmly);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet get = new HttpGet(accessTokenUrlXmly);
        try {
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String s = EntityUtils.toString(entity, "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                accessToken = (String) map.get("access_token");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取Access_token失败");
        }
        //获取jsapiTicket
        String ticket = "";
        HttpGet get2 = new HttpGet(jsApiTicketUrl.concat("access_token=" + accessToken + "&type=jsapi"));
        try {
            CloseableHttpResponse response = httpclient.execute(get2);
            if (response.getEntity() != null) {
                String s = EntityUtils.toString(response.getEntity(), "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                ticket = (String) map.get("ticket");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取jsApiTicket失败");
        }
        //获取signature
        String signature = "";
        String noncestr = UUID.randomUUID().toString();
        long time = System.currentTimeMillis();
        String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + time + "&url=" + url;
        signature = SHA1(str);
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", time);
        map.put("noncestr", noncestr);
        map.put("appId", appIdXmly);
        map.put("signature", signature);
        return map;
    }

    /**
     * 获取扫描条件信息（微信扫码）瑞翼
     *
     * @return
     */
    public static Map<String, Object> getScanCodeConditionRy(String url) {
        //获取Access-Token
        String accessToken = "";
        Map<String, Object> params = new HashMap<>();
        params.put("corpid", appIdRy);
        params.put("corpsecret", secretRy);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet get = new HttpGet(accessTokenUrlRy);
        try {
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String s = EntityUtils.toString(entity, "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                accessToken = (String) map.get("access_token");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取Access_token失败");
        }
        //获取jsapiTicket
        String ticket = "";
        HttpGet get2 = new HttpGet(jsApiTicketUrl.concat("access_token=" + accessToken + "&type=jsapi"));
        try {
            CloseableHttpResponse response = httpclient.execute(get2);
            if (response.getEntity() != null) {
                String s = EntityUtils.toString(response.getEntity(), "UTF-8");
                Map<String, Object> map = JSONObject.parseObject(s, Map.class);
                ticket = (String) map.get("ticket");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("获取jsApiTicket失败");
        }
        //获取signature
        String signature = "";
        String noncestr = UUID.randomUUID().toString();
        long time = System.currentTimeMillis();
        String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + time + "&url=" + url;
        signature = SHA1(str);
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", time);
        map.put("noncestr", noncestr);
        map.put("appId", appIdRy);
        map.put("signature", signature);
        return map;
    }


    /**
     * 进行SHA-1加密
     *
     * @param str
     * @return
     */
    public static String SHA1(String str) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        digest.update(str.getBytes());
        byte[] digest1 = digest.digest();
        StringBuffer buffer = new StringBuffer();
        //字节数组转换成十六进制位
        for (int i = 0; i < digest1.length; i++) {
            String shaHex = Integer.toHexString(digest1[i] & 0xFF);
            if (shaHex.length() < 2) {
                buffer.append(0);
            }
            buffer.append(shaHex);
        }
        return buffer.toString();
    }


    public static void main(String[] args) {
        String url = "aaa";
        Map<String, Object> scanCodeConditionXmly = getScanCodeConditionXmly(url);
        System.out.println(scanCodeConditionXmly.toString());

    }
}
